﻿/********************************************************
 // Module Name    : Run Time Show Window
 // Purpose        : Start Menu Item  
 // Class Used     : GlobalVariable.cs, CommonFunctions.cs
 // Created By     : Harwinder 
 // Date           : 13 jan 2009
**********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VAdvantage.Framework;
using VAdvantage.Logging;
using System.Threading;
using System.Data;
using VAdvantage.DataService;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Classes;
using VAdvantage.Utility;
using VAdvantage.DataService;
namespace VAdvantage.Apps
{
    public class AMenuStartItem : ASyncProcess
    {

        #region "Declaration"
        /**	The ID				*/
        private int _ID = 0;
        /* is Menu*/
        private bool _isMenu = false;
        /* name of menu item*/
        private String _name;
        /* calle Form */
        private IHost _host;
       
        /**/
        private long _action;

        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(AMenuStartItem).FullName);

        /* thread */
        private Thread _loader = null;
        /* BackGrnd Worker thread */
        private System.ComponentModel.BackgroundWorker _bWorker = null;
        #endregion


       
        public AMenuStartItem(int ID, bool isMenu, String name, IHost  aItem)
        {
            _ID = ID;
            _isMenu = isMenu;
            _name = name;
            _host = aItem;

            InitThread();
            //if (menu != null)
            //    m_increment = (menu.progressBar.getMaximum() - menu.progressBar.getMinimum()) / 5;
        }	//	



        /// <summary>
        /// Init Thread
        /// </summary>
        private void InitThread()
        {
            _bWorker = new System.ComponentModel.BackgroundWorker();
            _bWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(_bWorker_DoWork);
            _bWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_bWorker_RunWorkerCompleted);
            //_loader = new Thread(new ThreadStart(Run));
            //_loader.SetApartmentState(ApartmentState.STA);
        }

        //worker comlete
        void _bWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //System.Windows.Forms.MessageBox.Show("completed");
        }

        /// <summary>
        /// asyncronus processing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _bWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //for (long i = 0; i < 1000000000; i++) //e.Result =  this.Run();
            //{
            //    //////////
            //}
        }

        /// <summary>
        /// Start the thread
        /// </summary>
        public void Start()
        {
            //if (_loader != null)
            //{
            //    _loader.Start();
            //}

            //_bWorker.RunWorkerAsync();
           // System.Windows.Forms.Application.DoEvents();
            this.Run();
            //while(_bWorker.IsBusy)


        }

        /// <summary>
        ///	Start Menu Item
        /// </summary>
        /// 
        public void Run()
        {
            if (_host != null)
            {
                _host.ShowBusyIndicator = true;
            }

            Utility.Envs.TopExpander.IsExpanded = false; // Hide Top Menu on Any Action


            //m_timer.start();
            //SwingUtilities.invokeLater(m_updatePB);
            object oo = null;

            IDataReader dr = new DataReader();

            var client = Utility.AEnv.GetDataServiceClient();
            client.GetDataXMLCompleted += (sender, e) =>
                {

                    if (e.ServiceError == null)
                    {
                        try
                        {
                            dr.SetData(e.Result);

                            //SwingUtilities.invokeLater(m_updatePB);
                            if (dr.Read())	//	should only be one
                            {
                                String Action = Utility.Util.GetValueOfString(dr["Action"]);
                                int cmd;
                                if (Action.Equals("W"))				//	Window
                                {
                                    cmd = Utility.Util.GetValueOfInt(dr["AD_Window_ID"]);
                                    StartWindow(0, cmd);
                                }
                                else if (Action.Equals("P") || Action.Equals("R"))	//	Process & Report
                                {
                                    cmd = Utility.Util.GetValueOfInt(dr["AD_Process_ID"]);
                                    StartProcess(cmd);
                                }
                                else if (Action.Equals("B"))		//	Workbench
                                {
                                    cmd = Utility.Util.GetValueOfInt(dr["AD_Workbench_ID"]);
                                    StartWindow(cmd, 0);
                                }
                                else if (Action.Equals("F"))		//	WorkFlow
                                {
                                    if (_isMenu)
                                        cmd = Utility.Util.GetValueOfInt(dr["AD_Workflow_ID"]);
                                    else
                                        cmd = Utility.Util.GetValueOfInt(dr["Workflow_ID"]);

                                    if (_host != null)
                                    {
                                        _host.ShowBusyIndicator = false;
                                    }
                                    //if (_menu != null)
                                    //{
                                    //    _menu.startWorkFlow(cmd);
                                    //}
                                }
                                else if (Action.Equals("T"))		//	Task
                                {
                                    cmd = Utility.Util.GetValueOfInt(dr["AD_Task_ID"]);
                                    StartTask(cmd);
                                }
                                else if (Action.Equals("X"))		//	Form
                                {
                                    cmd = Utility.Util.GetValueOfInt(dr["AD_Form_ID"]);
                                    StartForm(cmd);
                                    //_host.ShowBusyIndicator = false;
                                }
                                else
                                    log.Log(Level.SEVERE, "No valid Action in ID=" + _ID);
                            }	//	for all records

                            //SwingUtilities.invokeLater(m_updatePB);
                            dr.Close();
                        }
                        catch (Exception er)
                        {
                            if (dr != null)
                            {
                                dr.Close();
                                dr = null;
                            }
                            log.Log(Level.SEVERE, "ID=" + _ID, er);
                            //Classes.ShowMessage.Error("Error", true, Utility.Msg.ParseTranslation(Utility.Envs.GetContext(), //e.Message));
                            //ADialog.error(0, null, "Error", Msg.parseTranslation(Env.getCtx(), e.getMessage()));
                            if (_host != null)
                            {
                                _host.ShowBusyIndicator = false;
                            }
                        }
                    }
                    else
                    {

                        ShowMessage.Error("Error?", true, e.ServiceError.ToString());
                        if (_host != null)
                        {
                            _host.ShowBusyIndicator = false;
                        }
                    }
                };

            String sql = "SELECT * FROM AD_Menu WHERE AD_Menu_ID=" + _ID;
            if (!_isMenu)
                sql = "SELECT * FROM AD_WF_Node WHERE AD_WF_Node_ID=" + _ID;

            client.GetDataXMLAsync(sql);

            // return oo;
            //try { Thread.Sleep(1000); }	//	.5 sec
            //catch (ThreadInterruptedException ie) { }

            //	ready for next
            //m_timer.stop();
            // SwingUtilities.invokeLater(m_resetPB);
            //if (_menu != null)
            //{
            //    //_menu.updateInfo();
            //    _menu.SetBusy(false);
            //}
            //if (_host != null)
            //{
            //    _host.ShowBusyIndicator = false;
            //}
        }	//	run

        /// <summary>
        ///Start Window
        /// </summary>
        /// <param name="AD_Workbench_ID"></param>
        /// <param name="AD_Window_ID"></param>
        internal void StartWindow(int AD_Workbench_ID, int AD_Window_ID)
        {


            if (Utility.Envs.ShowWindow(AD_Window_ID))
            {
                if (_host != null)
                {
                    _host.ShowBusyIndicator = false;
                }
                return;
            }

            //SwingUtilities.invokeLater(m_updatePB);
            AWindow frame = new AWindow();
            //frame.Explorer = _host.GetExplorer;
           // frame.SetBusyIndicator(_host);
           // frame.SetTitle(_name);

            bool OK = false;
            if (AD_Workbench_ID != 0)
                OK = frame.InitWorkbench(AD_Workbench_ID);
            else
                OK = frame.InitWindow(AD_Window_ID, null);	//	No Query Value
            if (!OK)
                return;

            //SwingUtilities.invokeLater(m_updatePB);			//	2

            //if (frame != null)
            //{
            //    //frame.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            //   // frame.Show();
            //}
            frame = null;
        }

        ///**
        // *	Start Process.
        // *  Start/show Process Dialog which calls ProcessCtl
        // *  @param AD_Process_ID	process
        // */
        internal void StartProcess(int AD_Process_ID)
        {
            ProcessDialog pd = new ProcessDialog(AD_Process_ID);
            pd.Explorer = _host.GetExplorer;
            //_host.GetProcessDialog.Visibility = System.Windows.Visibility.Visible;
           // pd.Closed += new EventHandler(pd_Closed);
            pd.Show();
        }

        void pd_Closed(object sender, EventArgs e)
        {
            if (_host != null)
            {
                _host.ShowBusyIndicator = false;
            }
        }

        ///**
        // *	Start OS Task
        // *  @param AD_Task_ID task
        // */
        internal void StartTask(int AD_Task_ID)
        {
           // System.Windows.MessageBox.Show("Task Pending");
            if (_host != null)
            {
                _host.ShowBusyIndicator = false;
            }
            //SwingUtilities.invokeLater(m_updatePB);			//	1
            ////	Get Command
            //MTask task = null;
            //String sql = "SELECT * FROM AD_Task WHERE AD_Task_ID=?";
            //try
            //{
            //    PreparedStatement pstmt = DB.prepareStatement(sql, null);
            //    pstmt.setInt(1, AD_Task_ID);
            //    ResultSet rs = pstmt.executeQuery();
            //    if (rs.next())
            //        task = new MTask(Env.getCtx(), rs, null);
            //    rs.close();
            //    pstmt.close();
            //}
            //catch (SQLException e)
            //{
            //    log.log(Level.SEVERE, sql, e);
            //}
            //if (task == null)
            //    return;

            //SwingUtilities.invokeLater(m_updatePB);			//	2
            //new ATask(m_name, task);
            //	ATask.start(m_name, task);
        }	//	startTask

        ///**
        // *	Start Form
        // *  @param AD_Form_ID form
        // */
        internal void StartForm(int AD_Form_ID)
        {

            //System.Windows.MessageBox.Show("Form Pending");
            //if (_host != null)
            //{
            //    _host.ShowBusyIndicator = false;
            //}

            if (AD_Form_ID == 115) // Tree Maintainance
            {
               // TreeMaintenance tree = new TreeMaintenance();
               // tree.Show();
                return;
            }
            if (AD_Form_ID == 117) //WorkFlowActivity
            {
                Apps.WF.WFActivity frmWfActivity = new VAdvantage.Apps.WF.WFActivity();
                Utility.Envs.RegisterWindowForm(frmWfActivity);
                Envs.ShowForm(frmWfActivity);
                if (_host != null)
                {
                    _host.ShowBusyIndicator = false;
                }
                return;
            }

            if (AD_Form_ID == 102) // Initial Tenant Setup
            {
                VSetup setup = new VSetup();
                Utility.Envs.RegisterWindowForm(setup);
                setup.Show();
                if (_host != null)
                {
                    _host.ShowBusyIndicator = false;
                }
                return;
            }

            FormFrame ff = new FormFrame();
            ff.OpenForm(AD_Form_ID);
            ff.Closing += new EventHandler<System.ComponentModel.CancelEventArgs>(ff_Closing);
           // ff.ShowDialog();
        }

        void ff_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
                
        }


        public void LockUI(ProcessInfo pi)
        {
            return;
        }

        public void UnlockUI(ProcessInfo pi)
        {
            return;
        }

        public bool IsUILocked()
        {
            return true;
        }

        public void ExecuteASync(ProcessInfo pi)
        {
            return;
        }
    }
}
